<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true">
      <el-form-item :label="t('candidate.fields.studentName')" prop="studentName">
        <el-input
          v-model="queryParams.studentName"
          :placeholder="t('common.inputTextPlaceholder') + t('candidate.fields.studentName')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-140px"
        />
      </el-form-item>
      <el-form-item :label="t('candidate.fields.jobCode')" prop="jobCode">
        <el-input
          v-model="queryParams.jobCode"
          :placeholder="t('common.inputTextPlaceholder') + t('candidate.fields.jobCode')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-140px"
        />
      </el-form-item>
      <el-form-item :label="t('candidate.fields.studentLevel')" prop="studentLevel">
        <el-select
          v-model="queryParams.studentLevel"
          :placeholder="t('common.selectTextPlaceholder') + t('candidate.fields.studentLevel')"
          clearable
          @change="handleQuery"
          class="!w-140px"
        >
          <el-option label="硕士研究生" value="硕士研究生" />
          <el-option label="博士研究生" value="博士研究生" />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('candidate.fields.researchDept')" prop="researchDept">
        <el-input
          v-model="queryParams.researchDept"
          :placeholder="t('common.inputTextPlaceholder') + t('candidate.fields.researchDept')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-140px"
        />
      </el-form-item>
      <el-form-item :label="t('candidate.fields.major')" prop="major">
        <el-input
          v-model="queryParams.major"
          :placeholder="t('common.inputTextPlaceholder') + t('candidate.fields.major')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-140px"
        />
      </el-form-item>
      <el-form-item :label="t('candidate.fields.awardMajor')" prop="awardMajor">
        <el-select
          v-model="queryParams.awardMajor"
          :placeholder="t('common.selectTextPlaceholder') + t('candidate.fields.awardMajor')"
          clearable
          @change="handleQuery"
          class="!w-140px"
        >
          <el-option label="材料加工工程" value="材料加工工程" />
          <el-option label="材料物理与化学" value="材料物理与化学" />
          <el-option label="材料学" value="材料学" />
          <el-option label="腐蚀科学与防护" value="腐蚀科学与防护" />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('candidate.fields.accountType')" prop="accountType">
        <el-select
          v-model="queryParams.accountType"
          :placeholder="t('common.selectTextPlaceholder') + t('candidate.fields.accountType')"
          clearable
          @change="handleQuery"
          class="!w-140px"
        >
          <el-option label="中国科大学生" value="中国科大学生" />
          <el-option label="联合培养学生" value="联合培养学生" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" />
          {{ t('common.search') }}
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" />
          {{ t('common.reset') }}
        </el-button>

        <!-- 初评 -->
        <template v-if="!isFinal">
          <!-- 初评-查看结果 -->
          <el-button
            type="success"
            @click="handleViewResult"
            :disabled="awardsInfo.judgeStatus === 1"
          >
            <Icon icon="ep:check" class="mr-5px" />
            {{ t('judgeScene.initial.viewResult') }}
          </el-button>
          <!-- 初评-导出结果 -->
          <el-button
            type="warning"
            plain
            @click="handleExportResult"
            :loading="exportLoading"
            :disabled="voteState !== 'IN_PROGRESS'"
          >
            <Icon icon="ep:download" class="mr-5px" />
            {{ t('judgeScene.initial.exportResult') }}
          </el-button>
        </template>

        <!-- 终评 -->
        <template v-if="isFinal">
          <!-- 终评-开启评委确认推荐名单 -->
          <el-button
            type="success"
            plain
            @click="handleStartJudgeConfirm"
            :disabled="!roundInfo.isJudgesConfirmBot || roundInfo.isJudgesConfirm"
          >
            <Icon icon="ep:open" class="mr-5px" />
            {{ t('judgeScene.final.startJudgeConfirm') }}
          </el-button>
          <!-- 终评-评委确认名单 -->
          <el-button
            type="success"
            plain
            @click="handleScxFinalJudgeConfirmList"
            :disabled="!roundInfo.isJudgesConfirmBot"
          >
            <Icon icon="ep:memo" class="mr-5px" />
            {{ t('judgeScene.final.judgeConfirmList') }}
          </el-button>
          <!-- 终评-查看结果 -->
          <el-button
            type="success"
            @click="handleViewResult"
            :disabled="awardsInfo.judgeStatus === 3"
          >
            <Icon icon="ep:check" class="mr-5px" />
            {{ t('judgeScene.final.viewResult') }}
          </el-button>
        </template>

        <!-- 通用 -->
        <!-- 查看评委结果提交情况 -->
        <el-button type="primary" plain @click="handleNotVoteJudge">
          <Icon icon="ep:question-filled" class="mr-5px" />
          {{ t('judgeScene.initial.viewJudgeSubmitResult') }}
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <vxe-toolbar ref="toolbarRef" custom />
    <vxe-table
      id="iJudge-table"
      ref="tableRef"
      v-loading="loading"
      :data="list"
      stripe
      :custom-config="vxeTableConfig"
      :column-config="{ resizable: true }"
      :size="vxeTableSize"
    >
      <vxe-column :title="t('common.index')" type="seq" field="seq" width="60" align="center" />
      <vxe-column
        :title="t('candidate.fields.jobCode')"
        field="jobCode"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('candidate.fields.studentName')"
        field="studentName"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('candidate.fields.gender')"
        field="gender"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('candidate.fields.researchDept')"
        field="researchDept"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('candidate.fields.mentorName')"
        field="mentorName"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      >
        <template #default="scope">
          <div class="flex items-center justify-center gap-[5px]">
            <span>{{ scope.row.mentorName }}</span>
            <el-tooltip
              v-if="scope.row.isInitialJudge || scope.row.isFinalJudge"
              effect="dark"
              placement="top"
            >
              <template #content>
                <div v-if="scope.row.isInitialJudge && scope.row.isFinalJudge">
                  {{ t('instance.index.initialAndFinal') }}
                </div>
                <div v-if="scope.row.isInitialJudge">
                  {{ t('instance.index.initialJudge') }}
                </div>
                <div v-if="scope.row.isFinalJudge">
                  {{ t('instance.index.finalJudge') }}
                </div>
              </template>
              <el-icon color="#ff0000" style="cursor: pointer">
                <WarningFilled />
              </el-icon>
            </el-tooltip>
          </div>
        </template>
      </vxe-column>
      <vxe-column
        :title="t('candidate.fields.secondaryMentorName')"
        field="secondaryMentorName"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('candidate.fields.major')"
        field="major"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('candidate.fields.awardMajor')"
        field="awardMajor"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('candidate.fields.studentLevel')"
        field="studentLevel"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('candidate.fields.awardLevel')"
        field="awardLevel"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('candidate.fields.accountType')"
        field="accountType"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('candidate.fields.applyDetail')"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      >
        <template #default="scope">
          <el-button link type="primary" @click="handleApplyDetail(scope.row)">
            {{ t('action.detail') }}
          </el-button>
        </template>
      </vxe-column>
      <vxe-column
        :title="t('candidate.fields.attachment')"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      >
        <template #default="scope">
          <el-button link type="primary" @click="handlePreview(scope.row)">
            {{ t('fileObjectDownload.buttonName') }}
          </el-button>
        </template>
      </vxe-column>
      <vxe-column
        :title="t('candidate.fields.initialScore')"
        field="initialScore"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('candidate.fields.finalScore')"
        field="finalScore"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('candidate.fields.processStatus')"
        field="processStatus"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      >
        <template #default="scope">
          <div v-if="scope.row.processStatus === 0"
            >{{ t('candidate.index.processStatus.underway') }}
          </div>
          <div v-if="scope.row.processStatus === 1"
            >{{ t('candidate.index.processStatus.passed') }}
          </div>
          <div v-if="scope.row.processStatus === 2"
            >{{ t('candidate.index.processStatus.failed') }}
          </div>
          <div v-if="scope.row.processStatus === 3"
            >{{ t('candidate.index.processStatus.draft') }}
          </div>
        </template>
      </vxe-column>
      <vxe-column
        :title="t('common.operate')"
        field="operator"
        align="center"
        fixed="right"
        width="100"
      >
        <template #default="scope">
          <el-button link type="primary" @click="handleViewResultDetail(scope.row)">
            {{ t('judgeScene.initial.resultDetail') }}
          </el-button>
        </template>
      </vxe-column>
    </vxe-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 申请详情 -->
  <CandidateApplicationInformation ref="awardStudentApplyInfoRef" />
  <JudgeResultForm ref="judgeFormRef" :stage-name="stageName" @refresh="getList" />
  <CandidateResultDetail ref="candidateResultDetailFormRef" />
  <JudgeResultList ref="judgeResultListRef" />
  <ScxFinalJudgeConfirmList ref="scxFinalJudgeConfirmListRef" />
  <!-- 文件预览弹窗 -->
  <FilePreviewDialog ref="filePreviewRef" type="pdf" />
</template>

<script setup lang="ts">
import { CandidateVO } from '@/api/awards/candidate'
import type { VxeTableInstance, VxeTablePropTypes, VxeToolbarInstance } from 'vxe-table'
import { useAppStore } from '@/store/modules/app'
import { WarningFilled } from '@element-plus/icons-vue'
import { CandidateAdminRespVO, ReviewSceneApi, RoundInfo } from '@/api/awards/reviewscene'
import download from '@/utils/download'
import JudgeResultForm from './JudgeResultForm.vue'
import CandidateResultDetail from '@/views/awards/candidate/components/CandidateResultDetail.vue'
import CandidateApplicationInformation from '@/views/awards/components/CandidateApplicationInformation.vue'
import FilePreviewDialog from '@/components/FilePreview/FilePreviewDialog.vue'
import JudgeResultList from './JudgeResultList.vue'
import ScxFinalJudgeConfirmList from '@/views/awards/scxfinalcandidate/components/ScxFinalJudgeConfirmList.vue'

/** 评 */
defineOptions({ name: 'Judge' })

const props = defineProps<{
  awardsId: string
  roundInfo: RoundInfo
  voteState: string
  stageName: string
}>()

const awardsInfo = inject('awardsInfo')

const route = useRoute()
const router = useRouter() // 路由对象
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const toolbarRef = ref<VxeToolbarInstance>()
const tableRef = ref<VxeTableInstance>()

const loading = ref(true) // 列表的加载中
const list = ref<CandidateAdminRespVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  awardsInstanceId: '', // 评奖ID
  studentLevel: undefined, // 培养层次
  awardLevel: undefined, // 评奖层次
  jobCode: undefined, // 学号
  major: undefined, // 专业
  awardMajor: undefined, // 评奖专业
  studentName: undefined, // 姓名
  accountType: undefined, // 学生类别
  researchDept: undefined, // 研究部
  roundId: '' // 终评轮次ID，初评阶段可不传
})
const queryFormRef = ref() // 搜索的表单

const vxeTableConfig: VxeTablePropTypes.CustomConfig = {
  storage: true,
  mode: 'drawer',
  checkMethod({ column }) {
    return !['seq', 'operator'].includes(column.field)
  }
}

const appStore = useAppStore()
const vxeTableSize = computed(() => appStore.getCurrentSizeVxe)

const filePreviewRef = ref<InstanceType<typeof FilePreviewDialog>>()
const handlePreview = (row: CandidateVO) => {
  filePreviewRef.value?.open(row.attachment)
}

const isFinal = computed(() => {
  return props.stageName && props.stageName === '终评'
})

/** 查询列表 */
const getList = async () => {
  loading.value = true
  queryParams.awardsInstanceId = props.awardsId
  queryParams.roundId = props.roundInfo.roundId ?? ''
  try {
    const data = await ReviewSceneApi.getCandidateAdmin(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

// 查看结果(初评+终评)
const judgeFormRef = ref<InstanceType<typeof JudgeResultForm>>()
const handleViewResult = () => {
  judgeFormRef.value?.open(props.awardsId, props.roundInfo.roundId ?? '')
}

// 导出结果(初评)
const exportLoading = ref(false)
const handleExportResult = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    queryParams.awardsInstanceId = props.awardsId
    queryParams.roundId = props.roundInfo.roundId ?? ''
    const data = await ReviewSceneApi.exportStudentAwardResult(queryParams)
    download.excel(data, props.stageName + '确认结果.xlsx')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

// 查看评委结果提交情况(初评+终评)
const judgeResultListRef = ref<InstanceType<typeof JudgeResultList>>()
const handleNotVoteJudge = () => {
  judgeResultListRef.value?.open(props.awardsId, props.roundInfo.roundId ?? '')
}

// ================== 终评功能 ==================

// 开启评委确认推荐名单
const startLoading = ref(false)
const handleStartJudgeConfirm = async () => {
  try {
    await message.confirm(t('judgeScene.final.startJudgeConfirmTips'))
  } catch {
    return
  }
  startLoading.value = true
  try {
    await ReviewSceneApi.openJudgesResults(props.awardsId, props.roundInfo.roundId ?? '')
    message.success(t('common.operSuccess'))
  } finally {
    startLoading.value = false
  }
}

// 评委确认名单
const scxFinalJudgeConfirmListRef = ref<InstanceType<typeof ScxFinalJudgeConfirmList>>()
const handleScxFinalJudgeConfirmList = () => {
  if (awardsInfo.value.awardsType === 0) {
    scxFinalJudgeConfirmListRef.value?.open(props.awardsId, props.roundInfo.roundId ?? '')
  } else if (awardsInfo.value.awardsType === 1) {
    // 师昌绪
    scxFinalJudgeConfirmListRef.value?.open(props.awardsId, props.roundInfo.roundId ?? '')
  } else {
    // 其他
    message.error('错误的评奖类型')
  }
}

// 表格中查看申请详情
const awardStudentApplyInfoRef = ref<InstanceType<typeof CandidateApplicationInformation>>()
const handleApplyDetail = (row: CandidateVO) => {
  awardStudentApplyInfoRef.value?.open(row.id)
}

// 查看推荐明细
const candidateResultDetailFormRef = ref<InstanceType<typeof CandidateResultDetail>>()
const handleViewResultDetail = (row: CandidateAdminRespVO) => {
  candidateResultDetailFormRef.value?.open(row, props.roundInfo.roundId ?? '')
}

/** 初始化 **/
onMounted(() => {
  getList()

  const table = tableRef.value
  const toolbar = toolbarRef.value
  if (table && toolbar) {
    table.connect(toolbar)
  }
})
</script>

<style lang="scss" scoped>
:deep(.vxe-cell .el-button + .el-button) {
  margin-left: 0;
}
</style>
